<?php
include 'checkSession.php';
$pageName = "";

$myMapLat = 26.927799;
$myMapLong = -82.055199;
$id=$_GET['id'];

if($id!=''){
$query = "SELECT * FROM Sign_Posts WHERE `sp_catalog_item_yesno` = '2' and sp_id='$id'";
$result = mysql_query($query);
if (!$result) {
}else{
$row = mysql_fetch_assoc($result);
$id=$row['sp_id'];
$zoom=15;
$myMapLat = $row['sp_latitude'];
$myMapLong = $row['sp_longitude'];
}
}else{
$id=0;
$zoom=12;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
	<title>Sign Inventory</title>
	<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
	<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
	<script type="text/javascript" src="js/markerclusterer.js"></script>
	<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
	
    <script type="text/javascript">
    //<![CDATA[
	
	var dev_marker;
	var add_marker;
	var sign_marker;
	var info_dialog;
	var cur_zoom;
	var map;
	
	

	
	        jQuery(window).ready(function(){
            jQuery("#watchPositionBtn").click(initiate_watchlocation);
            jQuery("#stopWatchBtn").click(stop_watchlocation);
        });

        var watchProcess = null;

        function initiate_watchlocation() {
          if (watchProcess == null) {
              watchProcess = navigator.geolocation.watchPosition(handle_geolocation_query, handle_errors);

          }
        }

        function stop_watchlocation() {
          if (watchProcess != null)
          {
              navigator.geolocation.clearWatch(watchProcess);
              watchProcess = null;
          }
        }

        function handle_errors(error)
        {
            switch(error.code)
            {
                case error.PERMISSION_DENIED: alert("user did not share geolocation data");
                break;

                case error.POSITION_UNAVAILABLE: alert("could not detect current position");
                break;

                case error.TIMEOUT: alert("retrieving position timedout");
                break;

                default: alert("unknown error");
                break;
            }
        }

        function handle_geolocation_query(position) {
		

 		  var lat=position.coords.latitude;
          var lng=position.coords.longitude;
          resize(lat,lng);

        }

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      }
    };
	
	var image_mark = new google.maps.MarkerImage('images/add_mark.png',
	new google.maps.Size(45, 65),
	new google.maps.Point(0,0),
	new google.maps.Point(25, 65));
	
	var sign_mark = new google.maps.MarkerImage('images/sign_post_icon.png',
	new google.maps.Size(64, 64),
	new google.maps.Point(0,0),
	new google.maps.Point(0, 0));

    function load() {
        map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(<? echo $myMapLat;?>, <? echo $myMapLong;?>),
		zoom: <? echo $zoom; ?>,
		tilt: 0,
		disableDoubleClickZoom: true,
		mapTypeId: google.maps.MapTypeId.SATELLITE,
      });
	  
	//google.maps.event.addListener(polygonObject,'dblclick',function(e){e.stop()});
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml.php", function(data) {
	  //downloadUrl("phpsqlajax_genxml.xml", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
		var my_markers = [];
		
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
		  var html = "<b>POST ID</b>:&nbsp;"+name+"<br/><b>LATITUDE</b>:&nbsp;"+markers[i].getAttribute("lat")+"<br/><b>LONGITUDE:&nbsp;</b>"+markers[i].getAttribute("lng")+"<br/><a target=\"_blank\" href=\"signPostManager.php?id="+name+"&action=edit\">CLICK HERE TO EDIT</a>";
          var icon = customIcons['bar'] || {};

		  
	  

		  

				
			if(name !=<? echo $id; ?>){
			var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow,
			draggable:true
          });
			my_markers.push(marker);	
			}else{
			var marker = new google.maps.Marker({
            map: map,
            position: point,
			zIndex: google.maps.Marker.MAX_ZINDEX + 1,
            icon: sign_mark,
			draggable:true
          });
			}
			
			          bindInfoWindow(marker, map, infoWindow, html,name);
			
					  google.maps.event.addListener(marker,'drag',function(event) {
					 var info = new google.maps.InfoWindow();
					 info.setContent("ADD NEW POST IN THIS POSIION<br/>LATITUDE:&nbsp;"+this.position.lat()+"<br/>LOGITITUDE:&nbsp;"+this.position.lng());	
				});
        }
		latLng = new google.maps.LatLng(0, 0);
		dev_marker = new google.maps.Marker({position: latLng, map: map} );


		

		
		var markerCluster = new MarkerClusterer(map, my_markers, {maxZoom: 16, gridSize: 100});
		
			google.maps.event.addListenerOnce(map, 'idle', function() {
				//map.setZoom(17);
			});
		
      });
	  
	google.maps.event.addListener(map, 'dblclick', function(event) {
	placeMarker(event.latLng);
	});
	


    }
	

	
	function placeMarker(location) {
	zoomLevel = map.getZoom();
	

	
	//if(zoomLevel>=18){
	add_marker = new google.maps.Marker({position: location, map: map, icon: image_mark} );
	//add_marker.setPosition(location);
	//}
		google.maps.event.addListener(add_marker, "click", function() {
	window.open('signPostManager.php?lng='+this.position.lng().toFixed(6)+'&lat='+this.position.lat().toFixed(6)+'&action=add');
	});
	
	}
	



    function bindInfoWindow(marker, map, infoWindow, html,name) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
	  

	  
	  
	  
	  
	  		google.maps.event.addListener(marker,'dragend',function() {
			var lat = this.position.lat().toFixed(6);
			var lng = this.position.lng().toFixed(6);
			info_dialog = new google.maps.InfoWindow();
			info_dialog.setContent("<table border='0' width='200'><tr><td colspan='2'><p align='center'>Update Marker position?</td></tr><tr><td width='143'><p align='right'><input type='button' value='Yes' name='yes'  onclick='update_data("+lat+","+lng+","+name+")'></td><td width='147'><p align='left'><input type='button' value='No' onclick='close_info()' name='no' style='float: left'></td></tr></table>");
			info_dialog.open(map,this);
				//window.location.href = 'signPostManager.php?lng='+this.position.lng().toFixed(5)+'&lat='+this.position.lat().toFixed(5)+'&id='+name+'&action=edit';
			});
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}
	
	function close_info(){
	//info_dialog.close();
	info_dialog.open(null,null);
	}
	
	function update_data(lat,lng,id){
	var url = "http://www.1or1000.com/sign-directory/update_geo_data.php?id=" + id + "&lat=" + lat + "&lng=" + lng;
	downloadUrl(url, function(data) {
	//if(data.length >=1) {
	info_dialog.setContent("Sign post Location Sucssfully Updated");
	//}
	});
	}

	
	function resize(lat,lng) {
	latLng = new google.maps.LatLng(lat, lng);
	map.panTo(latLng);

	dev_marker.setPosition( new google.maps.LatLng(lat, lng) );
	
	}

    //]]>
  </script>
</head>
<body onLoad="load()">
<!-- Header -->
<div id="header">
	<div class="shell">
		<!-- Logo + Top Nav -->
		<?php include "header-top.php";?>
		<!-- End Logo + Top Nav -->
		
		<!-- Main Nav -->
		<?php include "menu-tab.php";?>
		<!-- End Main Nav -->
	</div>
</div>
<!-- End Header -->

<!-- Container -->
<div id="container" style="height: auto">
	<div class="shell">
		
		<!-- Small Nav -->
		<div class="small-nav">
			<a href="#">Add Sign Post On Map</a>
			</div>
		<!-- End Small Nav -->
		
		<!-- Message OK -->
		<!-- End Message OK -->
        <!-- Message Error -->
        <!-- End Message Error -->
        <br />
		<!-- Main -->
		<div id="main">
			<div class="cl">&nbsp;</div>
			
			<!-- Content -->
			<div id="content" style="width:930px;">
				
				<!-- Box -->
				<!-- End Box -->
                <!-- Box -->
<div class="box">
					<!-- Box Head -->
					<div class="box-head">
						<h2>Add Sign Post On Map</h2>
					</div>
					<!-- End Box Head -->
					
					
						
				<div style="height:600px;">
				<button id="watchPositionBtn" >Watch Current Position</button>
				<button id="stopWatchBtn" >Stop Watch Position</button>
				 <div id="map" style="width: 930px; height: 550px"></div>
				</div>	
				
			  </div>
				<!-- End Box -->

		  </div>
			<!-- End Content -->
			
			<!-- Sidebar -->
			<!-- End Sidebar -->
<div class="cl">&nbsp;</div>			
		</div>
		<!-- Main -->
	</div>
</div>
<!-- End Container -->

<!-- Footer -->
<?php include 'footer.php';?>
<!-- End Footer -->
	
</body>
</html>